import { connect, Link } from 'umi';
import { RouteContext, GridContent } from '@ant-design/pro-layout';
import {
    Descriptions,
    Card,
    Row,
    Col,
    List,
    Typography,
    Space,
    Skeleton,
    Tabs,
    message
} from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import styles from './style.less';
import { MessageOutlined, LikeOutlined, StarOutlined } from '@ant-design/icons';
import UserBrief from '@/components/UserBrief'
import EditAble from '../../../../components/EditAble'
import ProjectStatus from '../ProjectStatus'
import RichText, { RichTextEdit } from '@/components/RichText'
import ArrayUtils from '@/utils/ArrayUtils'
import { STATUS } from '@/consts/project'
import { updateProject } from '@/services/project/project'
import ProjectComment from '@/pages/projects/components/ProjectComment'
import ProjectItemLog from '@/pages/projects/components/ProjectItemLog'
import { pageDemand } from '@/services/project/demand'
import { pageProd } from '@/services/project/prod'

const { TabPane } = Tabs;
const { Paragraph } = Typography;


const ProjectDetail = (props) => {

    const {
        projectId,
        dispatch,
        projectPermission,
        projectDetailData = {},
        userPage,
        myInfo,
    } = props;

    const [permission,setPermission] = useState({
        edit:false
    })

    useEffect(() => {
        if (projectId) {
            dispatch({
                type: 'project/getProjectDetail',
                payload: projectId
            });
            dispatch({
                type: 'project/listUser',
                payload: {
                    projectId: projectId,
                    params: {
                        pageSize: 5
                    }
                }
            })
            pageDemand(projectId, { pageSize: 3, }).then(({ data }) => {
                setDemandPageData(data)
            })
            pageProd(projectId, { pageSize: 3 }).then(({ data }) => {
                setProdPage(data)
            })
          
        }
    }, [projectId])

    useEffect(() => {
        setProjectDetail(projectDetailData)
        setPermission({
            edit: (projectPermission?.edit || projectDetailData.userId === myInfo.id ) && true ,
            manage:projectPermission?.manage && true,
            delete: projectPermission?.delete && true,
        })
    }, [projectDetailData])

    if (projectDetailData?.name) {
        document.title = projectDetailData.name
    }
    const [isDetailTextEditFalg, setIsDetailTextEditFlag] = useState(false);
    const [projectDetail, setProjectDetail] = useState(projectDetailData);
    const [projectLogUpdate, setProjectLogUpdate] = useState(0);
    const [tabKey, setTabKey] = useState()
    const [demandPageData, setDemandPageData] = useState();
    const [prodPage, setProdPage] = useState();

    const articalData = {
        list: [],
        totalCnt: 10
    };
    for (let index = 0; index < 2; index++) {
        articalData.list.push({
            id: index,
            likeCnt: index + 100,
            replyCnt: index,
            title: "B加项目",
            description: "B加项目B加项目B加项目B加项目B加项目",
            content: "B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目B加项目"
        })
    }

    const memberRender = (<>
        <List
            grid={{
                gutter: 8,
                column: 2,
                xs: 1,
                sm: 1,
                md: 1,
                lg: 1,
                xl: 2,
                xxl: 2,
            }}
            dataSource={userPage && userPage.list}
            renderItem={item => (
                <UserBrief user={item.user} role={item.roleName}></UserBrief>
            )}
        >
        </List>
    </>);
    const IconText = ({ icon, text }) => {
        return (
            <span >
                <Space>
                    {icon}
                    {text}
                </Space>
            </span>
        )
    }

    const articalRender = (
        <>
            <List
                dataSource={articalData.list}
                itemLayout="vertical"
                renderItem={item => (
                    <List.Item
                        key={item.id}
                        actions={[
                            <IconText icon={<LikeOutlined></LikeOutlined>} text={item.likeCnt} key="like" />,
                            <IconText icon={<MessageOutlined></MessageOutlined>} text={item.replyCnt} key="list-vertical-message" />,
                        ]}
                    >
                        <List.Item.Meta
                            title={<a href={item.href}>{item.title}</a>}
                            description={item.description}
                        />
                        <div style={{
                            textIndent: 12
                        }}>
                            {item.content}
                        </div>
                    </List.Item>
                )}
            >
            </List>
        </>
    );

    const prodRender = (
        <>
            <List
                dataSource={prodPage?.list}
                className={styles.projectItemList}
                key="id"
                loading={!prodPage}
                itemLayout="vertical"
                renderItem={item => (
                    <List.Item key={item.id} >
                        <List.Item.Meta
                            title={<Link to={`/projects/${projectId}/prod/${item.id}`}>{item.name}</Link>}
                            description={item.description}
                        />
                    </List.Item>
                )}
            >
            </List>
        </>
    )

    const demandRender = (
        <>
            <List
                dataSource={demandPageData?.list}
                className={styles.projectItemList}
                key="id"
                loading={!demandPageData}
                itemLayout="vertical"
                renderItem={item => (
                    <List.Item key={item.id}>
                        <List.Item.Meta
                            title={<Link to={{
                                pathname: `/projects/${projectId}/demand/${item.id}`,
                            }}>{item.name}</Link>}
                            description={item.description}
                        />
                    </List.Item>
                )}
            >
            </List>
        </>
    )

    const saveProject = (data) => {
        updateProject(projectId, data).then(({ success }) => {
            if (success) {
                message.success("保存成功")
            }
            if (tabKey === "log") {
                setProjectLogUpdate(projectLogUpdate + 1)
            }
        })
    }

    const updateName = (value) => {
        saveProject({
            name: value,
            oldData: {
                name: projectDetail.name
            }
        })
        projectDetail.name = value;
        setProjectDetail({
            ...projectDetail,
        })
    }

    const updateProjectDesc = (value) => {
        saveProject({
            description: value,
            oldData: {
                description: projectDetail.description
            }
        })
        projectDetail.description = value;
        setProjectDetail({ ...projectDetail })
    }

    const updateProjectStatus = (value) => {
        saveProject({
            status: value,
            oldData: {
                status: projectDetail.status
            }
        })
        projectDetail.status = value;
        setProjectDetail({ ...projectDetail })
    }

    const updateProjectUser = (value, user) => {
        if (value === projectDetail.userId) {
            return
        }
        console.log(value, user)
        saveProject({
            userId: value,
            payload: {
                userId: user.nickName
            },
            oldData: {
                userId: projectDetail.userId,
                payload: {
                    userId: projectDetail.user?.nickName
                }
            }
        })
        projectDetail.userId = value;
        projectDetail.user = user
        setProjectDetail({ ...projectDetail })
    }

    const updateProjectContent = (content) => {
        setIsDetailTextEditFlag(false)
        const oldDataContent = {
            content: {
                text: projectDetail.content.text
            }
        };
        saveProject({
            content: content,
            oldData: oldDataContent
        })
        projectDetail.content = content;
        setProjectDetail({ ...projectDetail })
    }

    const projectDesc = (
        <Descriptions size="small" column={2}>
            <Descriptions.Item span={2}>
                <EditAble permission={permission}
                    value={projectDetail.name}
                    onSave={updateName}
                    type="input">
                    <h1>{projectDetail.name}</h1>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item label="负责人">
                <EditAble permission={permission}
                    value={projectDetail.userId}
                    editComponentProps={{
                        projectId: projectId,
                        defaultOpen: true
                    }}
                    onSave={updateProjectUser}
                    type="userSelect">
                    <UserBrief user={projectDetail.user}></UserBrief>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
                <EditAble permission={permission}
                    value={projectDetail.status}
                    editComponentProps={{
                        options: ArrayUtils.jsonToArray(STATUS).map(item => {
                            return { value: item.key, label: item.value.name }
                        }),
                        defaultOpen: true
                    }}
                    onSave={updateProjectStatus}
                    type="select">
                    <ProjectStatus status={projectDetail.status}></ProjectStatus>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间" span={2}>{projectDetail.createTime}</Descriptions.Item>
            <Descriptions.Item label="概述" span={2} >
            </Descriptions.Item>
            <Descriptions.Item span={2} >
                <EditAble permission={permission}
                    editComponentProps={{
                        rows: 4,
                        maxLength: 200,
                        showCount: true,
                    }}
                    width='100%'
                    onSave={updateProjectDesc}
                    value={projectDetail.description}
                    type="textarea">
                    <p>
                        {projectDetail.description}
                    </p>
                </EditAble>
            </Descriptions.Item>
        </Descriptions >
    );

    return <>
        <GridContent className={styles.content}>
            <React.Fragment>
                <Row gutter={[8, 8]} >
                    <Col span={16}>
                        <Card>
                            {projectDetail.name ? projectDesc : <Skeleton />}
                        </Card>
                        <Card
                            title="详细内容"
                        >
                            {projectDetail.content ?
                                <EditAble permission={permission}
                                    isEdit={isDetailTextEditFalg}
                                    onEdit={() => {
                                        setIsDetailTextEditFlag(true)
                                    }}
                                    value={projectDetail.content.raw}
                                    onCancel={() => {
                                        setIsDetailTextEditFlag(false)
                                    }}
                                    onSave={() => {
                                        setIsDetailTextEditFlag(false)
                                    }}
                                    useCustomOperate={true}
                                    editComponent={
                                        <RichTextEdit
                                            onCancel={() => {
                                                setIsDetailTextEditFlag(false)
                                            }}
                                            onSave={updateProjectContent}
                                            value={projectDetail.content.raw}>
                                        </RichTextEdit>
                                    }>
                                    <RichText
                                        ellipsis
                                        value={projectDetail.content.text}>
                                    </RichText>
                                </EditAble>
                                : <Skeleton />
                            }
                        </Card>


                        <Card
                            title="文档"
                            extra={<a href="#">更多</a>}
                        >
                            {articalRender}
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            title="项目成员"
                            extra={<Space><div>总数：{userPage && userPage.count}</div><Link to={`/projects/${projectId}/member`}>更多</Link></Space>}
                        >
                            {memberRender}
                        </Card>
                        <Card
                            title="迭代"
                            extra={<Space><div>总数：{prodPage?.count || 0}</div><Link to={`/projects/${projectId}/prod`}>更多</Link></Space>}
                        >
                            {prodRender}
                        </Card>
                        <Card
                            title="需求"
                            extra={<Space><div>总数：{demandPageData?.count || 0}</div><Link to={`/projects/${projectId}/demand`}>更多</Link></Space>
                            }
                        >
                            {demandRender}
                        </Card>
                        <Card style={{ minHeight: "240px" }}>
                            <Tabs
                                activeKey={tabKey}
                                tabBarGutter={-8}
                                tabBarStyle={{ margin: 0 }}
                                onChange={(tabKey) => {
                                    setTabKey(tabKey)
                                }}
                            >
                                <TabPane tab="评论" key="comment">
                                    <ProjectComment projectId={projectId} bizId={projectId} bizType="project" />
                                </TabPane>
                                <TabPane tab="日志" key="log">
                                    <ProjectItemLog
                                        projectId={projectId}
                                        itemId={projectId}
                                        update={projectLogUpdate}
                                        renderField={(value, fieldName) => {
                                            if (fieldName === "status") {
                                                return <ProjectStatus status={value}></ProjectStatus>
                                            }
                                        }}
                                        itemType="project" />
                                </TabPane>
                            </Tabs>
                        </Card>
                    </Col>
                </Row>
            </React.Fragment>
        </GridContent>
    </>

}


export default connect(({ project,user }) => ({
    projectDetailData: project.projectDetail,
    userPage: project.userPage,
    myInfo:user.myInfo
}))(ProjectDetail);